library lz_http;

import 'dart:convert';
import 'package:dio/dio.dart';

 class HttpManager {
  static HttpManager? _instance;
  HttpManager._();
  static HttpManager get instance {
    _instance ??= HttpManager._();
    return _instance!;
  }

  Map<String, dynamic>? _headers;
  set headers (Map<String, dynamic> value) {
    if (value != null) {
      dio.options.headers = _headers;
    }
  }

  Dio dio = Dio();
  HttpManager () {
    dio.options.connectTimeout = 5000 as Duration? ; //请求超时限制
    dio.options.receiveTimeout = 3000 as Duration? ;
    dio.interceptors.add(LogInterceptor(requestBody: true));//是否开启请求日志
  }

  // get请求
  get(String url, params, Function successCallBack, Function failCallBack) async {
    requestWithMethond(url, 'get', params, successCallBack, failCallBack);
  }

  // 普通post请求
  post(String url, params, Function successCallBack,
      Function failCallBack) async {
    requestWithMethond(url, 'post', params, successCallBack, failCallBack);
  }

  postJson (String url, params, Function successCallBack,
      Function failCallBack) async {
    requestWithMethond(url, 'postJson', params, successCallBack, failCallBack);

  }

  requestWithMethond(String url , String method , FormData params , Function successCallBack , Function failCallBack) async {
    Response response;
    try {
      if (method == 'get') {
        if (params != null) {
          response = await dio.get(url,
              queryParameters: Map.fromEntries(params.fields));
        } else {
          response = await dio.get(url);
        }
      } else if (method == 'post') {
        if (params != null && params.fields.isNotEmpty) {
          response = await dio.post(url, data: params);
        } else {
          response = await dio.post(url);
        }
      } else if (method == 'postJson') {
        if (params != null && params.fields.isNotEmpty) {
          response = await dio.post(url, data: jsonEncode(params));
        } else {
          response = await dio.post(url);
        }
      }
    } on DioException catch (error) {
      Response? errorResponse;
      if (error.response != null) {
        errorResponse = error.response;
      }
      _error(failCallBack,error.message);
    }
  }
 }

// 请求错误返回
_error(Function failCallBack, String? error) {
  if (failCallBack != null) {
    failCallBack(error);
  }
}
